package com.concurrent.chapter2.concurrent03;

import java.util.concurrent.CountDownLatch;
/*
 * 比赛全过程demo
 */
public class MyThread extends Thread {
	private static final int THREAD_NUM = 10;//线程数 
	private CountDownLatch comingTag;
	private CountDownLatch waitTag;
	private CountDownLatch waitRunTag;
	private CountDownLatch beginTag;
	private CountDownLatch endTag;
	public MyThread(CountDownLatch comingTag, CountDownLatch waitTag, CountDownLatch waitRunTag, CountDownLatch beginTag, CountDownLatch endTag) {
		super();
		this.comingTag = comingTag;
		this.waitTag = waitTag;
		this.waitRunTag = waitRunTag;
		this.beginTag = beginTag;
		this.endTag = endTag;
	}

	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() + "运动员正在赶往起点。。。");
			Thread.sleep((int)(Math.random() * 10000));
			comingTag.countDown();
			System.out.println(Thread.currentThread().getName() + "等待裁判说准备。。。");
			waitTag.await();
			System.out.println(Thread.currentThread().getName() + "预备。。。");
			Thread.sleep((int)(Math.random() * 10000));
			waitRunTag.countDown();
			beginTag.await();
			System.out.println(Thread.currentThread().getName() + "起跑。。。" + System.currentTimeMillis());
			Thread.sleep((int)(Math.random() * 10000));
			System.out.println(Thread.currentThread().getName() + "到达终点。。。");
			endTag.countDown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			CountDownLatch comingTag = new CountDownLatch(THREAD_NUM);
			CountDownLatch waitTag = new CountDownLatch(1);
			CountDownLatch waitRunTag = new CountDownLatch(THREAD_NUM);
			CountDownLatch beginTag = new CountDownLatch(1);
			CountDownLatch endTag = new CountDownLatch(THREAD_NUM);
			MyThread[] threads = new MyThread[THREAD_NUM];//每个运动员一个线程
			for (int i = 0; i < threads.length; i++) {
				threads[i] = new MyThread(comingTag, waitTag, waitRunTag, beginTag, endTag);
				threads[i].start();
			}
			System.out.println("裁判员正在等待选手到场。。。");
			comingTag.await();
			System.out.println("裁判员看到全部运动员已到场。。。准备5秒。。。");
			Thread.sleep(5000);
			waitTag.countDown();
			System.out.println("各就各位，预备。。。");
			waitRunTag.await();
			System.out.println("发令枪响起。。。");
			beginTag.countDown();
			endTag.await();
			System.out.println("所有运动员到达终点，比赛结束。。。");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
